<?php

/**
 * Result 组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Result extends Cola
{
    public static $called = FALSE;
	
    protected $isAjax = FALSE;
	
    protected $delay = 1;
	
    public function delay($time)
    {
        $this->delay = $time;
        return $this;
    }
	
    public function setAjax($isAjax)
    {
        $this->isAjax = $isAjax;
        return $this;
    }
	
    /**
	set(0, '登录成功');
	set(1, '密码错误');
	set(-1, '数据库连接失败');
	
	code:
		< 0 全局错误，比如：系统错误：数据库丢失连接/文件不可读写
		= 0 正确
		> 0 || 字符串 一般业务逻辑错误，可以定位到具体控件，比如：用户名为空/密码为空
	 
     */
    public function set($code, $msg, $data = NULL)
    {
		$vars = array(
		    'code'   => $code,
			'msg'    => $msg,
			'data'   => $data
		);
		
	    // 防止 Widget_Result 内部出现错误死循环
	    self::$called ? exit(Json::encode($vars)) : self::$called = TRUE;
		
		// 插件接口
		//HOOK PLUG_Result($vars, $this);

        if ($this->request->isAjax() || $this->isAjax) {
            $this->response->json($vars);
        } else {

			$location = isset($data['location']) ? $data['location'] : Common::backUrl();
//exit($location);
			if($this->delay > 0) {
                $body = '<!DOCTYPE html>';
                $body .= '<html>';
                $body .= '<head>';
                $body .= '<meta charset="'. Common::$charset .'">';
                $body .= '<meta http-equiv="refresh" content="' . $this->delay . ';URL='. $location .'" />';
                $body .= '</head>';
                $msg && $body .= '<body>' . $msg . '</body>';
                $body .= '</html>';	
				
			    $this->response
				    ->status($code)
				    ->write($body)
				    ->send();
			} else {
				$this->response->redirect($location, $code);
			}
        }
    }

}
